//
//  BaseController.swift
//  TrafficViolation
//
//  Created by eaglelive on 2017/4/12.
//  Copyright © 2017年 eaglelive. All rights reserved.
//

import Foundation
import UIKit
import Alamofire
import SwiftyJSON
class BaseController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        automaticallyAdjustsScrollViewInsets = false
        self.navigationController?.navigationBar.isHidden = true//隐藏导航
        let tap = UITapGestureRecognizer(target: self, action: #selector(hideKeyBoard))
        tap.cancelsTouchesInView = false
        self.view.addGestureRecognizer(tap)
    }
    //点击空白回收键盘
    func hideKeyBoard() {
        view.endEditing(true)
    }
    func AddToolBar() -> UIToolbar {
        let toolBar:UIToolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: kScreenW, height: 35))
        toolBar.backgroundColor = UIColor.gray
        let spaceBtn = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        let barBtn = UIBarButtonItem(title: "完成", style: .plain, target: self, action: #selector(hideKeyBoard))
        toolBar.items = [spaceBtn, barBtn]
        return toolBar
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.isHidden = true//隐藏导航
    }
    //自定义导航 appearWay 当前页弹出方式1：root切换，2：pop出来的，3：present出来的
    func setupNavBar(title:String,isback:Bool,appearWay:Int,isright:Bool) {
        let backgroundView = UIView();
        backgroundView.frame = CGRect(x: 0, y: 0, width: kScreenW, height: kNavigationBarH + kStatusBarH);
        backgroundView.backgroundColor = appMainColor
        self.view.addSubview(backgroundView)
        if isback {
            let leftButton = UIButton(type: UIButtonType.custom)
            leftButton.frame = CGRect(x: 0, y: 20, width: 60, height: 44);
            leftButton.setImage(UIImage(named: "back_btn"), for: .normal)
            leftButton.titleLabel?.font = UIFont.systemFont(ofSize: 25)
            leftButton.tag = appearWay
            leftButton.addTarget(self, action: #selector(leftButtonClick(sender:)), for: .touchUpInside)
            backgroundView.addSubview(leftButton)
        }
        if isright {
            let rightButton = UIButton(type: UIButtonType.custom)
            rightButton.frame = CGRect(x: kScreenW - 60, y: 22, width: 60, height: 44);
            rightButton.setImage(UIImage(named: "help"), for: .normal)
            rightButton.titleLabel?.font = UIFont.systemFont(ofSize: 25)
            rightButton.addTarget(self, action: #selector(rightButtonClick(sender:)), for: .touchUpInside)
            backgroundView.addSubview(rightButton)
        }
        let titleLabel = UILabel()
        titleLabel.center = CGPoint(x: self.view.center.x, y: 42)
        titleLabel.bounds = CGRect(x: 0, y: 0, width: 200, height: 44)
        titleLabel.textColor = UIColor.white
        titleLabel.text = title;
        titleLabel.textAlignment = NSTextAlignment.center
        backgroundView.addSubview(titleLabel)
    }
    /*返回按钮点击事件*/
    func leftButtonClick(sender: UIButton) {
        if 1 == sender.tag{
            let mainVC = UINavigationController(rootViewController: LoginController())
            app.window?.rootViewController = mainVC
        }
        if 2 == sender.tag{
            self.navigationController?.popViewController(animated: true)
        }
        if 3 == sender.tag{
            self.dismiss(animated: true, completion: nil)
        }
    }
    //帮助
    func rightButtonClick(sender: UIButton){
        self.present(VerifyCarHelp(), animated: true, completion: nil)
    }
    // 前端验证提醒
    func checkAlertFun(message:String) {
        let alertController = UIAlertController(title: alertTitle, message: message, preferredStyle: .alert)
        let cancelAction = UIAlertAction(title: "确定", style: .cancel, handler: nil)
        alertController.addAction(cancelAction)
        self.present(alertController, animated: true, completion: nil)
    }
    //操作失败提醒
    func failOperNoticeFun(code:String,message:String){
        let alertController = UIAlertController(title: alertTitle, message: message, preferredStyle: .alert)
        if("000" == code){
            let okAction = UIAlertAction(title: "去登录", style: .default, handler:{
                (UIAlertAction) -> Void in
                if(PersonalModel.deletePersonal(userID: userID! as! String)){
                    let userDefault = UserDefaults.standard
                    userDefault.removeObject(forKey: "userID")
                    userDefault.removeObject(forKey: "tokenID")
                    userDefault.removeObject(forKey: "isEmployee")
                    let mainVC = UINavigationController(rootViewController: LoginController())
                    app.window?.rootViewController = mainVC
                }
            })
            alertController.addAction(okAction)
        }else{
            let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
            alertController.addAction(cancelAction)
        }
        self.present(alertController, animated: true, completion: nil)
    }
    //显示html文件
    func loadHtmlView(type:String){
        if reachability.isReachable {
            let webview = UIWebView()
            webview.frame = CGRect(x:0,y:kStatusBarH + kNavigationBarH,width:kScreenW,height:kScreenH - kStatusBarH - kNavigationBarH)
            let urlString = "\(projectUrl)/source/list/\(type)/\(userID!)?tokenID=\(tokenID!)&tokenUserID=\(userID!)" //网络请求地址
            Alamofire.request(urlString, method: .get, parameters: nil, headers : headers).responseJSON { (response) in
                if response.result.isSuccess{
                    let json = JSON(response.result.value as! [String : AnyObject])
                    if json["success"] == true {
                        if json["rdata"].count > 0{
                            let sourceID = json["rdata"][0]["sourceFileID"]
                            let  url = URL(string:"\(projectUrl)/file/download/\(sourceID)?tokenID=\(tokenID!)&tokenUserID=\(userID!)")
                            let request :URLRequest = URLRequest.init(url: url!)
                            webview.loadRequest(request)
                            self.view.addSubview(webview)
                        }
                    }
                    else{
                        print("获取常见问题出错啦!\(json["rdata"])")
                        self.failOperNoticeFun(code: json["rcode"].rawString()!, message: json["rdata"].rawString()!)
                    }
                }
                else{
                    print("获取常见问题出错：\(response.result.error!)") //输出错误日志
                }
            }
        }else{
            let alertController = UIAlertController(title: alertTitle, message: netNotice, preferredStyle: .alert)
            let cancelAction = UIAlertAction(title: "确定", style: .cancel, handler: nil)
            alertController.addAction(cancelAction)
            self.present(alertController, animated: true, completion: nil)
        }
    }
    //抢单、完成订单使用
    func toOperatOrder(url:String){
        if reachability.isReachable {
            Alamofire.request(url, method: .post, parameters: nil, headers : headers).responseJSON { (response) in
                if response.result.isSuccess{
                    let json = JSON(response.result.value as! [String : AnyObject])
                    if json["success"] == true {
                        let alertController = UIAlertController(title: alertTitle, message: json["rdata"].rawString()!, preferredStyle: .alert)
                        let okAction = UIAlertAction(title: "确定", style: .cancel, handler: {(UIAlertAction) -> Void in
                            self.dismiss(animated: true, completion: nil)
                        })
                        alertController.addAction(okAction)
                        self.present(alertController, animated: true, completion: nil)
                    }else{
                        self.failOperNoticeFun(code: json["rcode"].rawString()!, message: json["rdata"].rawString()!)
                    }
                }
                else{
                    print(response.result.error!) //输出错误日志
                }
            }
        }else{
            let alertController = UIAlertController(title: alertTitle, message: netNotice, preferredStyle: .alert)
            let cancelAction = UIAlertAction(title: "确定", style: .cancel, handler: nil)
            alertController.addAction(cancelAction)
            self.present(alertController, animated: true, completion: nil)
        }
    }
    //生成预付费订单
    func weiXin(orderNo:String,money:String,orderType:String){
        if WXApi.isWXAppInstalled() {
           weixinPay(orderNo:orderNo,money:money,orderType:orderType)
        }else{
            let alertController = UIAlertController(title: alertTitle, message: "您的手机还未安装微信", preferredStyle: .alert)
            let okAction = UIAlertAction(title: "安装", style: .default, handler:{
                (UIAlertAction) -> Void in
                let weixinUrl = WXApi.getWXAppInstallUrl()
                UIApplication.shared.openURL(URL(string: weixinUrl!)!)
            })
            alertController.addAction(okAction)
            let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
            alertController.addAction(cancelAction)
            
        }
    }
    //发起微信支付
    func weixinPay(orderNo:String,money:String,orderType:String) {
        if reachability.isReachable {
            let urlString = "\(projectUrl)/pay/commit/wx/\(orderType)/\(userID!)?tokenID=\(tokenID!)&tokenUserID=\(userID!)" //网络请求地址
            let parameter:[String:Any] = [
                "orderNo":orderNo,
                "totalCash":money
            ]
            Alamofire.request(urlString, method: .post, parameters: parameter, headers : headers).responseJSON { (response) in
                if response.result.isSuccess{
                    let json = JSON(response.result.value as! [String : AnyObject])
                    if json["success"] == true {
                        let req = PayReq()
                        req.partnerId = json["rdata"]["partnerid"].rawString()!
                        req.prepayId = json["rdata"]["prepayid"].rawString()!
                        req.package = json["rdata"]["package"].rawString()!
                        req.nonceStr = json["rdata"]["noncestr"].rawString()!
                        let timestamp = json["rdata"]["timestamp"].rawString()!
                        req.timeStamp = UInt32(Int(timestamp)!)
                        req.sign = json["rdata"]["sign"].rawString()!
                        WXApi.send(req)
                        payNo = orderNo
                        payMoney = money
                    }
                    else{
                        print("预付费订单出错啦!\(json["rdata"])")
                        self.failOperNoticeFun(code: json["rcode"].rawString()!, message: json["rdata"].rawString()!)
                    }
                }
                else{
                    print("出错：\(response.result.error!)") //输出错误日志
                }
            }
        }else{
            let alertController = UIAlertController(title: alertTitle, message: netNotice, preferredStyle: .alert)
            let cancelAction = UIAlertAction(title: "确定", style: .cancel, handler: nil)
            alertController.addAction(cancelAction)
            self.present(alertController, animated: true, completion: nil)
        }
        
    }
}
